<?php

namespace Activity;

use C\L\WebController;
use C\M\Share;

class ShareController extends WebController
{
    protected function init()
    {
        $this->service = $this->s_activity_share;

        $this->createKeys = [
        'uid', 'image',
        ];
    }

    protected function beforeCreate(&$data)
    {
        $data['uid'] = $this->uid;
        return true;
    }

    public function applyAction()
    {
        $image = $this->getValue('image', true, 'string');
        $userId = $this->uid;

        $now = time();
        $startDate   = mktime(0, 0, 0, date("m", $now), date("d", $now), date("Y", $now));
        $endDate     = mktime(0, 0, 0, date("m", $now), date("d", $now) + 1, date("Y", $now));

        try {
            $hasSuccessRecord = $this->s_activity_share->findSuccessRecord($userId, $startDate, $endDate);
            if ($hasSuccessRecord) {
                throw new \Exception('本日奖励已发放，无需重复上传');
            }

            $share = new Share;
            $share->status = 'S';
            $share->uid    = $userId;
            $share->image  = $image;
            $result = $share->save();
            if (!$result) {
                return $this->error();
            }

            $config = $this->s_config->get('activity_share');
            $isEnabledAutoReview = $config['auto_review'] ?? false;

            if ($share->id && $isEnabledAutoReview) {
                $this->s_activity_share->review($share->id, 'Y');
            }

            return $this->success();
        } catch (\Exception $error) {
            return $this->error($error->getMessage());
        }
    }
}
